package com.fcmeditech.AsianSexyGirls.customgallery;

	import android.content.Context;
	import android.graphics.Matrix;
	import android.graphics.PointF;
	import android.graphics.RectF;
	import android.util.AttributeSet;
	import android.util.FloatMath;
	import android.util.Log;
	import android.view.*;
	import android.widget.Gallery;
import android.widget.ImageView;

public class ZoomingLimitGallery extends Gallery
	{	private Context mContext;
	    //variables for zoom limit and pan bounds    
	    private float[] mMatrixValues = new float[9];
	    private float mMaxZoom = 2f;
	    private float mMinZoom = 0.75f;
	    private RectF mViewRect;

	    //variables for multi-touch    
	    private Matrix mMatrix = new Matrix();
	    private Matrix mSavedMatrix = new Matrix();
        //Operation Mode
	    static final int NONE = 0;
	    static final int TAP = 1;
	    static final int DRAG = 2;
	    static final int ZOOM = 3;
	    int mMode = NONE;
        //Check the item position
	    boolean first=true;
		float k=1;
		int currentPage=0,previousPage=0;
		
	    private PointF mStart = new PointF();
	    private PointF mMid = new PointF();

	    private float mOldDist = 1f;
	    MotionEvent mStartEvent;
	    
	    ImageView myImageView;
/****************Constructor******************************************/
	    public ZoomingLimitGallery(Context context)
	    {
	        super(context);
	        mContext = context;
	    }
	    public ZoomingLimitGallery(Context context, AttributeSet attrs,int defStyle) {
			super(context, attrs, defStyle);
			// TODO Auto-generated constructor stub
		}

		public ZoomingLimitGallery(Context context, AttributeSet attrs) {
			super(context, attrs);
			// TODO Auto-generated constructor stub
		}
/*************************Turn off Scroll**************************************/
	  	@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
			// TODO Auto-generated method stub
			//return super.onScroll(e1, e2, distanceX, distanceY);
			return false;
		}
/*************************Touching Processing**************************************/	    
	  	@Override    
	    public boolean onTouchEvent(MotionEvent event)
	    {
	        myImageView = (ImageView) super.getSelectedView();
	       
	        mViewRect = new RectF(0, 0, myImageView.getWidth(), myImageView.getHeight()); 
	        
	        /*******Check the Position of Image in List*******/
	        currentPage=getSelectedItemPosition();
	       
	        Log.e("Position","Item Position = "+ currentPage);//
	        Log.e("Position","Item Previous Position = "+ previousPage);//
	       
	        if(currentPage!=previousPage)
	        {     previousPage=currentPage;
	        	  mMatrix.reset();
	        	  Log.e("Position","Matrix is reset = "+ mMatrix.toString());//
	        	  mSavedMatrix.reset();
	        	  first=true;
	        	  k=1;
	        }
           /***************************************************/
	        switch (event.getAction() & MotionEvent.ACTION_MASK)
	        {
	            case MotionEvent.ACTION_DOWN:
	                mSavedMatrix.set(mMatrix);
	                /********Adjust K gain********************/
	                mMatrix=myImageView.getImageMatrix();
	                Log.e("TAP","initMatrix:"+mMatrix.toString());
	               
	                if(first==true)
		            {
		            	mMatrix.getValues(mMatrixValues);
		            	float originScale = mMatrixValues[Matrix.MSCALE_X];
		            	Log.e("Adjusment Factor","originScale= "+String.valueOf(originScale));
		            	if(originScale!=0) k=1/originScale;
		            	Log.e("Adjusment Factor","k= "+String.valueOf(k));
		            	first=false;
		            }
	                
	                mStart.set(event.getX(), event.getY()); //--->start point
	                mMode = TAP;
	                break;

	            case MotionEvent.ACTION_POINTER_DOWN:
	                mOldDist = DistanceCalculating(event);
	                if (mOldDist > 10f)
	                {
	                    mSavedMatrix.set(mMatrix); 
	                    midPoint(mMid, event);
	                    mMode = ZOOM;
	                }
	                break;

	            case MotionEvent.ACTION_UP:
	                if (mMode == TAP)
	                {
	                    mMatrix.reset(); 
	                    mMode = NONE;
	                    
	                }
	                previousPage=currentPage;//
	                break;

	            case MotionEvent.ACTION_POINTER_UP:
	                mMode = NONE;
	                break;

	            case MotionEvent.ACTION_MOVE:
	                /*****************PANNING****************/
	            	if (mMode == TAP || mMode == DRAG)
	                { Log.d("Moving","---DRAGGING---");
	                   
	                    mMode = DRAG;
	                    mMatrix.set(mSavedMatrix);

	                    // limit pan boundary                    
	                    mMatrix.getValues(mMatrixValues);
	                    float currentY = mMatrixValues[Matrix.MTRANS_Y];
	                    float currentX = mMatrixValues[Matrix.MTRANS_X];
	                    float currentScale = mMatrixValues[Matrix.MSCALE_X];
	                    float currentHeight = myImageView.getHeight() * currentScale*k;
	                    float currentWidth = myImageView.getWidth() * currentScale*k;
	                    float dx = event.getX() - mStart.x;
	                    float dy = event.getY() - mStart.y;
	                    float newX = currentX+dx;
	                    float newY = currentY+dy;

	                    RectF drawingRect = new RectF(newX, newY, newX+currentWidth, newY+currentHeight);
	                    float diffUp = Math.min(mViewRect.bottom-drawingRect.bottom, mViewRect.top-drawingRect.top);
	                    float diffDown = Math.max(mViewRect.bottom-drawingRect.bottom, mViewRect.top-drawingRect.top);
	                    float diffLeft = Math.min(mViewRect.left-drawingRect.left, mViewRect.right-drawingRect.right);
	                    float diffRight = Math.max(mViewRect.left-drawingRect.left, mViewRect.right-drawingRect.right);
	                    if(diffUp > 0)
	                    {
	                        dy += diffUp;
	                    }
	                    if(diffDown < 0)
	                    {
	                        dy += diffDown;
	                    }
	                    if(diffLeft > 0)
	                    {
	                        dx += diffLeft;
	                    }
	                    if(diffRight < 0)
	                    {
	                        dx += diffRight;
	                    }
	                    mMatrix.postTranslate(dx, dy);
	                    myImageView.setImageMatrix(mMatrix);
	        	        Log.d("Moving","Image Set!OK");
	        	        myImageView.invalidate();

	                }
	                /******************ZOOMING*******************************/
	                else if (mMode == ZOOM)
	                {   Log.d("Moving","---ZOOMING---");
	                    float newDist = DistanceCalculating(event);//--->calculate new Distance
	                    if (newDist > 1.0f)
	                    {
	                        mMatrix.set(mSavedMatrix);
	                        
	                        float scale = newDist / mOldDist;
	                        Log.d("Moving","Scale:"+String.valueOf(scale));
	                        // limit zoom
	                        mMatrix.getValues(mMatrixValues);
	                        Log.d("Moving","First Matrix---"+mMatrix.toString());
	                        float currentScale = mMatrixValues[Matrix.MSCALE_X];//-->get the first value of Matrix at position 1x1(=scale1*scale2*...)
	                       if (scale * currentScale > mMaxZoom)
	                        {
	                            scale = mMaxZoom / currentScale;//--->limit the maxScale=2.0f
	                        }
	                        else if (scale * currentScale < mMinZoom)
	                        {
	                            scale = mMinZoom / currentScale; //--->limit the maxScale=0.75f
	                        }
	                        mMatrix.postScale(scale, scale, mMid.x, mMid.y);
	                        Log.d("Moving","CurrentScale:"+String.valueOf(currentScale));
	                        }
	                    myImageView.setImageMatrix(mMatrix);
	        	        Log.d("Moving","Image Set!OK");
	        	        myImageView.invalidate();
	                }
	        }
	   	       
	        return true;
	    }
/*******************Sub method****************************************/
	    /** Determine the space between the first two fingers */    
	    private float DistanceCalculating(MotionEvent event)
	    {
	        float x = event.getX(0) - event.getX(1);
	        float y = event.getY(0) - event.getY(1);
	        return FloatMath.sqrt(x * x + y * y);
	    }
 
	    /** Calculate the mid point of the first two fingers */    
	    private void midPoint(PointF point, MotionEvent event)
	    {
	        float x = event.getX(0) + event.getX(1);
	        float y = event.getY(0) + event.getY(1);
	        point.set(x / 2, y / 2);
	    }
	}//End

